<template>
    <div class="app-container" v-loading="loading">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="触达配置标题" prop="cdName">
              <el-input v-model="form.cdName" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="判断类型" prop="cdType" >
            <el-select v-model="form.cdType" placeholder="请选择判断类型" @change="onCdTypeChange" :disabled="id!==''">
              <el-option label="客户状态" value="STATUS" />
              <el-option label="日期" value="DAYS" />
            </el-select>
          </el-form-item>
          <el-form-item label="客户状态" prop="cdCrmState" v-if="form.cdType=='STATUS'">
              <el-select v-model="form.cdCrmState" placeholder="请选择客户状态" @change="onCdCrmStateChange">
                <el-option 
                  v-for="dict in custStatusOptions"
                  :key="dict.LOOKUP_CODE"
                  :label="dict.LOOKUP_NAME"
                  :value="dict.LOOKUP_CODE">
                </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="客户装修进度" prop="cdCrmZxjd" v-if="form.cdType=='STATUS'">
              <el-select v-model="form.cdCrmZxjd" placeholder="请选择客户装修进度"  @change="onCdCrmZxjdChange">
                <el-option 
                  v-for="dict in zxStatusOptions"
                  :key="dict.LOOKUP_CODE"
                  :label="dict.LOOKUP_NAME"
                  :value="dict.LOOKUP_CODE">
                </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="日期" prop="cdAddDays" v-if="form.cdType=='DAYS'">
            <div class="number-box">
              客户企业微信添加后<el-input v-model="form.cdAddDays" placeholder="请输入" type="number"/>天时间，发送消息给客户
            </div>
          </el-form-item>

          <el-form-item label="渠道" prop="cdYl3" v-if="form.cdType=='STATUS'">
              <el-select v-model="form.cdYl3" placeholder="请选择渠道" @change="onChannelChange">
                <el-option 
                  v-for="dict in channelOptions"
                  :key="dict.LOOKUP_CODE"
                  :label="dict.LOOKUP_NAME"
                  :value="dict.LOOKUP_CODE">
                </el-option>
              </el-select>
          </el-form-item>

          <el-form-item label="销区" prop="cdYl2" v-if="form.cdType">
            <el-input v-model="form.cdYl2" placeholder="请输入销区" @focus="showXqSelector()" readonly/>
          </el-form-item>

          <el-form-item label="品牌" prop="cdPp" v-if="form.cdType">
              <el-select v-model="form.cdPp" placeholder="请选择品牌" @change="onCdPpChange">
                <el-option 
                  v-for="dict in brandOptions"
                  :key="dict.BRAND_CODE"
                  :label="dict.BRAND_NAME"
                  :value="dict.BRAND_CODE">
                </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="组织架构" prop="cdYl5Name" v-if="form.cdType">
              <div class="cdYl5Name"  @click="isShowDeptSelector=true">{{ form.cdYl5Name || '请选择组织架构+' }}</div>
          </el-form-item>
          <el-form-item label="文本内容" prop="cdContent" v-if="form.cdType">
              <el-input type="textarea" v-model="form.cdContent" placeholder="请输入文本内容" row="5" resize="vertical"/>
          </el-form-item>
          <div class="form-title" v-if="form.cdType">小程序信息：</div>
          <el-form-item label="标题" prop="cdMiniTitle" v-if="form.cdType">
              <el-input v-model="form.cdMiniTitle" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="小程序APPID" prop="cdMiniAppid" v-if="form.cdType">
              <el-input v-model="form.cdMiniAppid" placeholder="请输入小程序APPID" />
          </el-form-item>
          <el-form-item label="小程序URL" prop="cdMiniUrl" v-if="form.cdType">
              <el-input v-model="form.cdMiniUrl" placeholder="请输入小程序URL" />
          </el-form-item>
          <div class="form-title" v-if="form.cdType">图片信息：</div>
          <el-form-item label="图片信息" prop="cdImgUrls" v-if="form.cdType">
              <!-- <el-input v-model="form.cdImgUrls" placeholder="请输入触达图片信息" /> -->
              <el-upload :action="uploadAction" :headers="uploadHeaders" :file-list="imageList" list-type="picture-card" :on-success="handleUploadSucc" :before-upload="()=>{this.loading=true}">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                    <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview" @click="handlePicPreview(file)">
                            <i class="el-icon-zoom-in"></i>
                        </span>
                        <span class="el-upload-list__item-delete" @click="handlePicRemove(file)">
                            <i class="el-icon-delete"></i>
                        </span>
                    </span>
                </div>
                </el-upload>
          </el-form-item>
          <!-- <el-form-item label="触达标题" prop="cdName">
              <el-input v-model="form.cdName" placeholder="请输入触达标题" />
          </el-form-item>
          <el-form-item label="触达品牌名称" prop="cdPpName">
              <el-input v-model="form.cdPpName" placeholder="请输入触达品牌名称" />
          </el-form-item>
          <el-form-item label="触达小程序标题" prop="cdMiniTitle">
              <el-input v-model="form.cdMiniTitle" placeholder="请输入触达小程序标题" />
          </el-form-item>
          <el-form-item label="触达小程序APPID" prop="cdMiniAppid">
              <el-input v-model="form.cdMiniAppid" placeholder="请输入触达小程序APPID" />
          </el-form-item>
          <el-form-item label="触达小程序URL" prop="cdMiniUrl">
              <el-input v-model="form.cdMiniUrl" placeholder="请输入触达小程序URL" />
          </el-form-item>
          <el-form-item label="触达图片信息" prop="cdImgUrls">
              <el-input v-model="form.cdImgUrls" placeholder="请输入触达图片信息" />
          </el-form-item>
          <el-form-item label="触达预留1" prop="cdYl1">
              <el-input v-model="form.cdYl1" placeholder="请输入触达预留1" />
          </el-form-item>
          <el-form-item label="触达预留2" prop="cdYl2">
              <el-input v-model="form.cdYl2" placeholder="请输入触达预留2" />
          </el-form-item>
          <el-form-item label="触达预留3" prop="cdYl3">
              <el-input v-model="form.cdYl3" placeholder="请输入触达预留3" />
          </el-form-item>
          <el-form-item label="触达预留4" prop="cdYl4">
              <el-input v-model="form.cdYl4" placeholder="请输入触达预留4" />
          </el-form-item>
          <el-form-item label="触达预留5" prop="cdYl5">
              <el-input v-model="form.cdYl5" placeholder="请输入触达预留5" />
          </el-form-item> -->
          <el-form-item>
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
          </el-form-item>
        </el-form>

        <el-dialog :visible.sync="showPicPreview">
            <img width="100%" :src="picPreviewUrl" alt="">
        </el-dialog>

        <el-dialog title="选择销区" :visible.sync="isShowXqSelector" append-to-body>
          <el-form ref="form" :model="xqSelector" label-width="120px">
            <el-form-item label="一级销区" prop="xq1">
                <el-select v-model="xqSelector.xq1" placeholder="请选择一级销区" @change="onChangeXq1">
                    <el-option
                        v-for="dict in xqSelector.xq1Options"
                        :key="dict.RP02"
                        :label="dict.RP02NAME"
                        :value="dict.RP02"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="二级销区" prop="xq2">
                <el-select v-model="xqSelector.xq2" placeholder="请选择二级销区" @change="onChangeXq2">
                    <el-option
                        v-for="dict in xqSelector.xq2Options"
                        :key="dict.RP03"
                        :label="dict.RP03NAME"
                        :value="dict.RP03"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitXqSelector()">确 定</el-button>
              <el-button @click="closeXqSelector()">取 消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>

        <el-dialog
          title="组织架构"
          :visible.sync="isShowDeptSelector">
          <div class="dept-tree" v-loading="deptLoading">
            <el-tree ref="deptTree" :data="deptTree" :props="{label:'label',children:'children'}" :expand-on-click-node="true" :show-checkbox="true" @check="onDeptCheck" :check-strictly="false" node-key="hrDeptId" :default-checked-keys="deptDefaultChecked"></el-tree>
          </div>
          <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitDeptSelector()">确 定</el-button>
              <el-button @click="closeDeptSelector()">取 消</el-button>
          </div>
        </el-dialog>
    </div>
  </template>
  
  <script>
  import { getCdinfo, addCdinfo, updateCdinfo } from "@/api/khcd/cdinfo";
  import { getId } from "@/api/common";
  import { treeselect } from "@/api/system/dept";
  import requestCrm from '@/utils/requestCrm';
  import requestQy from '@/utils/requestQy';
  
  export default {
    name: "cdinfoEdit",
    data() {
      return {
        id:'',
        // 遮罩层
        loading: false,
        custStatusOptions:[],
        zxStatusOptions:[],
        brandOptions:[],
        channelOptions:[],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          cdType: [{ required: true, message: "请选择判断类型", trigger: "blur" }],
          cdCrmState: [],
          cdAddDays: [],
          cdContent: [{ required: true, message: "请输入文本内容", trigger: "blur" }],
        },
        imageList:[],
        uploadAction:"",
        uploadHeaders: {
          Authorization: 'Bearer ' + this.$store.state.user.token,
          lesseeId: this.$store.state.user.lesseeid || '13'
        },
        showPicPreview:false,
        picPreviewUrl:'',
        isShowXqSelector:false,
        xqSelector:{
          xq1Options:[],
          xq2Options:[],
          xq1:'',
          xq1Name:'',
          xq2:'',
          xq2Name:''
        },
        isShowDeptSelector:false,
        deptLoading:false,
        deptTree:[],
        deptDefaultChecked:[],
        deptDefaultCheckedNode:[]
      };
    },
    beforeRouteLeave(to, from, next) {
      this.clearCache()
      next()
    },
    created() {
      this.id = this.$route.query.id||''
      this.loading = true
      if(!this.id){
          this.createId(id =>{
            this.loading = false
              this.form.id = id
              this.uploadAction =  process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+id+"&sourcessType=CDINFO_IMG"
          })
      }else{
        getCdinfo(this.id).then(response => {
          this.loading = false
          this.deptDefaultCheckedNode = []
          this.deptDefaultChecked = response.data.cdYl5?response.data.cdYl5.split(','):''
          if(response.data.cdDeptList&&response.data.cdDeptList.length){
            response.data.cdDeptList.forEach(i => {
              this.deptDefaultCheckedNode.push({
                hrDeptId: i.hrDeptId,
                label: i.deptName
              })
              response.data.cdYl5Name = response.data.cdYl5Name?response.data.cdYl5Name + ',' + i.deptName : i.deptName
            });
          }
          this.form = response.data;
          this.imageList = JSON.parse(this.form.cdImgUrls)
          this.uploadAction =  process.env.VUE_APP_BASE_API+"/common/upload/news?sourcessId="+this.form.id+"&sourcessType=CDINFO_IMG"
        });
      }
      this.getLookUpInfo('HN_FOLLOW_PROID', (res)=>{
        this.custStatusOptions = res
      })
      this.getLookUpInfo('LABEL_INSTALL_PLAN', (res)=>{
          this.zxStatusOptions = res
      })
      this.getLookUpInfo('CUST_CREATE_TYPE', (res)=>{
          this.brandOptions = res
      })
      this.getLookUpInfo('HN_CUST_CHANNEL', (res)=>{
          this.channelOptions = res
      })
      this.getBrandOptions()
      this.getDeptTree()
    },
    methods: {
      getDeptTree() {
        let that = this
        that.deptTree = []
        that.deptLoading = true
        treeselect().then(function (res) {
          that.deptLoading = false
          if(res.code == 200){
            res.data[0].disabled = true
            that.deptTree = res.data
          }
        })
      },
      onDeptCheck(data, checked, indeterminate){
        this.deptDefaultChecked = []
        this.deptDefaultCheckedNode = []
        checked.checkedNodes.forEach(i => {
          if(!i.children||!i.children.length){
            this.deptDefaultCheckedNode.push(i)
            this.deptDefaultChecked.push(i.hrDeptId)
          }
        });
      },
      submitDeptSelector(){
        this.form.cdYl5Name = ''
        this.form.cdYl5 = this.deptDefaultChecked.join(',')
        this.deptDefaultCheckedNode.forEach(i => {
          this.form.cdYl5Name = this.form.cdYl5Name ? this.form.cdYl5Name + ',' + i.label : i.label
        });
        this.isShowDeptSelector = false
      },
      closeDeptSelector(){
        this.isShowDeptSelector = false
      },
      createId(call){
          getId().then(response => {
              if(call){
                  call(response.data.id)
              }
          })
      },
      getLookUpInfo(lookupcode, call){
        requestCrm({
            url:'WxService?method=LookupInfoByLookupCode',
            method: 'post',
            data: {
                lookupcode
            }
        }).then(res=>{
            if(call){
                call(res.data)
            }
        })
      },
      getBrandOptions(){
        requestCrm({
            url:'WxService?method=crmGetBrandAllList',
            method: 'post',
            data: {}
        }).then(res=>{
            this.brandOptions = res.data
        })
      },
      getQyImageUrl(imgUrl, call){
        requestQy({
            url:'WxService?method=wxUploadImgToQywx',
            method: 'post',
            data: {imgUrl}
        }).then(res=>{
            if(call){
              call(res.data)
            }
        })
      },
      onCdTypeChange(e){
        if(e=='STATUS'){
          this.rules.cdCrmState = [{ required: true, message: "请选择客户状态", trigger: "blur" }]
          this.rules.cdAddDays = []
        }else if(e=='DAYS'){
          this.rules.cdCrmState = []
          this.rules.cdAddDays = [{ required: true, message: "请输入日期", trigger: "blur" }]
        }
      },
      onCdCrmStateChange(e){
        console.log(e)
      },
      onCdCrmZxjdChange(e){
        console.log(e)
      },
      onCdPpChange(e){
        console.log(e)
        this.form.cdPpName = this.brandOptions.find(obj=>{
          return obj.BRAND_CODE == e
        }).BRAND_NAME
      },
      // 取消按钮
      cancel() {
        // this.$store.dispatch("tagsView/delView", this.$route)
        this.$router.go(-1)
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          isActive: undefined,
          lesseeId: undefined,
          cdName: undefined,
          cdType: undefined,
          cdPp: undefined,
          cdPpName: undefined,
          cdCrmState: undefined,
          cdCrmZxjd: undefined,
          cdAddDays: undefined,
          cdContent: undefined,
          cdMiniTitle: undefined,
          cdMiniAppid: undefined,
          cdMiniUrl: undefined,
          cdImgUrls: undefined,
          cdYl1: undefined,
          cdYl2: undefined,
          cdYl3: undefined,
          cdYl4: undefined,
          cdYl5: undefined,
          cdYl5Name: undefined
        };
        this.resetForm("form");
      },
      clearCache(){
        // let cache = this.$vnode.parent.componentInstance.cache
        // let key = ""
        // for(var prop in cache){
        //   console.log(cache[prop].componentInstance.$route.path)
        //   console.log(this.$route.path)
        //   if(cache[prop].componentInstance.$route.path == this.$route.path){
        //     key = prop
        //     break
        //   }
        // }
        // console.log(key)
        // console.log(cache)
        // if(key){
        //   delete cache[key]
        // }
        // this.$destroy()
      },
      /** 提交按钮 */
      submitForm: function() {
        this.form.cdImgUrls = JSON.stringify(this.imageList) 
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.id) {
              updateCdinfo(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  // this.$store.dispatch("tagsView/delView", this.$route)
                  this.$router.go(-1)
                }
              });
            } else {
              addCdinfo(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  // this.$store.dispatch("tagsView/delView", this.$route)
                  this.$router.go(-1)
                }
              });
            }
          }
        });
      },

      handleUploadSucc(response, file, fileList) {
        // console.log('上传的文件:');
        console.log(response);
        console.log(file);
        console.log(fileList);
        console.log(this.imageList);
        this.getQyImageUrl(response.url, (res)=>{
          this.loading = false
          this.imageList.push({
            url: response.url,
            imgUrl: response.url,
            qyImgUrl: res.qyImgUrl
          })
        })
      },
      handlePicPreview(file) {
        this.picPreviewUrl = file.imgUrl
        this.showPicPreview = true
      },
      handlePicRemove(file) {
        let i = this.imageList.findIndex((item) => {
          return item.imgUrl == file.imgUrl
        })
        if(i > -1){
          this.imageList.splice(i, 1)
        }
      },
      getXQ1Options(call){
          requestCrm({
              url:'WxService?method=getXQ1ByMemCode',
              method: 'post',
              data: {memCode:'HN029163'}
          }).then(res=>{
              this.xqSelector.xq1Options = res.data
              if(call){
                  call()
              }
          })
      },
      getXQ2Options(xq1code, call){
          requestCrm({
              url:'WxService?method=getXQ2ByMemCodeAndXQ1',
              method: 'post',
              data: {xq1code, memCode:'HN029163'}
          }).then(res=>{
              this.xqSelector.xq2Options = res.data
              if(call){
                  call()
              }
          })
      },
      onChangeXq1(e){
          let xq1 = this.xqSelector.xq1Options.find(obj=>{
              return e == obj.RP02
          })
          if(xq1){
              this.xqSelector.xq1Name = xq1.RP02NAME
              this.xqSelector.xq1 = xq1.RP02
              this.xqSelector.xq2 = ''
              this.xqSelector.xq2Name = ''
              this.getXQ2Options(xq1.RP02)
          }
      },
      onChangeXq2(e){
          let xq2 = this.xqSelector.xq2Options.find(obj=>{
              return e == obj.RP03
          })
          if(xq2){
              this.xqSelector.xq2 = xq2.RP03
              this.xqSelector.xq2Name = xq2.RP03NAME
          }
      },
      showXqSelector(){
        this.isShowXqSelector = true
        this.xqSelector.xq1Options = []
        this.xqSelector.xq2Options = []
        this.xqSelector.xq1 = ''
        this.xqSelector.xq1Name = ''
        this.xqSelector.xq2 = ''
        this.xqSelector.xq2Name = ''
        this.getXQ1Options()
      },
      closeXqSelector(){
        this.isShowXqSelector = false
      },
      submitXqSelector(){
        this.form.cdYl1 = this.xqSelector.xq2
        this.form.cdYl2 = this.xqSelector.xq2Name
        this.isShowXqSelector = false
      },
      onChannelChange(e){
        let item = this.channelOptions.find(obj=>{
              return e == obj.LOOKUP_CODE
        })
        this.form.cdYl3 = item.LOOKUP_CODE
        this.form.cdYl4 = item.LOOKUP_NAME
      }
    }
  };
  </script>
  <style>
    .number-box{
      display: flex;
      align-items: center;
      vertical-align: middle;
      float: left;
      font-size: 14px;
      color: #606266;
      box-sizing: border-box;
    }
    .number-box .el-input input{
      width: 100px;
    }
    .number-box .el-input{
      flex: 0 0 100px;
      margin: 0 10px;
    }
    .form-title{
      font-size: 20px;
      font-weight: bold;
      margin-left: 20px;
      margin-bottom: 20px;
    }

    .dept-tree{
      height: 400px;
      overflow: auto;
    }
    .cdYl5Name{
      line-height: 38px;
      cursor: pointer;
    }
  </style>